﻿using System;
using System.Collections.Generic;
using System.Data;

using SiteUnity.Frame.Common.Tools.Class;
using SiteUnity.Layers.Core.Connection.Database;
using SiteUnity.Layers.Entity.General;

namespace SiteUnity.Layers.Core.Provider
{
    public class GeneralProvider : Provider
    {
        public GeneralProvider()
        {
            SetDefaultConnection();
        }

        public List<Website> selectWebsites()
        {   
            Database.clear();
            DataTable datatable = Database.executeQuery("SU_selectWebsites");

            return ClassMapper.ToClassList<Website>(datatable);
        }

        public List<WebsiteSetting> selectWebsiteSettingAll(Website website)
        {
            Database.clear();
            Database.addParameter("@website_guid", website.Guid);

            DataTable datatable = Database.executeQuery("SU_selectWebsiteSettingAll");
            Database.close();

            return ClassMapper.ToClassList<WebsiteSetting>(datatable);
        }

        public Website selectWebsite(Website website)
        {
            website = new Website();

            Database.clear();
            Database.addParameter("@guid", website.Guid);
            DataRow datarow = Database.executeQuery("SU_selectWebsite").Rows[0];

            website = ClassMapper.ToClass<Website>(datarow);

            website.Pages = new List<Page>();
            website.Pages.AddRange(selectPage(website));

            Database.close();

            foreach (Page page in website.Pages)
            {
                if (page.ParentGuid != default(Guid))
                    page.ParentPage = ClassCollection.Find<Page>(website.Pages, "Guid", page.ParentGuid);

                page.ChildPages = ClassCollection.FindAll<Page>(website.Pages, "ParentGuid", page.Guid);
            }

            return website;
        }

        public List<Page> selectRecentPage(Website website, int count)
        {
            Database.clear();
            Database.addParameter("@website_guid", website.Guid);
            Database.addParameter("@count", count);

            DataTable datatable = Database.executeQuery("SU_selectRecentPage");
            Database.close();

            return ClassMapper.ToClassList<Page>(datatable);
        }

        private List<Page> selectPage(Website website)
        {
            Database.clear();
            Database.addParameter("@website_guid", website.Guid);

            DataTable datatable = Database.executeQuery("SU_selectPage");

            return ClassMapper.ToClassList<Page>(datatable);
        }

        public List<PageType> selectPageType()
        {
            Database.clear();
            DataTable datatable = Database.executeQuery("SU_selectPageType");
            Database.close();

            return ClassMapper.ToClassList<PageType>(datatable);
        }
    }
}
